<?php

namespace common\models\user;

use Yii;
use common\helpers\ArrayHelper;
use common\models\trend\TrendLog;

/**
 * This is the model class for table "{{%user_trend}}".
 *
 * @property int $id 用户ID
 * @property int $level_id 等级
 * @property int $experience 经验值
 * @property int $credit 积分
 * @property int $gold 金币
 * @property int $cash 余额
 * @property int $liveness 用户活力值
 * @property int $likes 获赞
 * @property string $gis 空间位置信息
 * @property string $geohash
 * @property int $located_at 定位时间
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class UserTrend extends \common\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_trend}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['id'], 'required'],
            [['id', 'level_id', 'experience', 'credit', 'likes', 'gold', 'cash', 'liveness', 'located_at', 'created_at', 'updated_at'], 'integer'],
            [['gis'], 'safe'],
            [['geohash'], 'string', 'max' => 20],
            [['id'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'level_id' => 'Level ID',
            'experience' => 'Experience',
            'credit' => 'credit',
            'gold' => 'gold',
            'cash' => 'cash',
            'liveness' => 'Liveness',
            'likes' => 'likes',
            'gis' => 'Gis',
            'geohash' => 'Geohash',
            'located_at' => 'Created At',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function getLevel() {
        return $this->hasOne(\common\models\trend\TrendLevel::className(), ['id' => 'level_id']);
    }

    public static function updateLocation($uid, $location) {
        $model = static::findOrNew($uid);
        if ($model->isNewRecord) {
            $model->id = $uid;
        }
        $model->setGeometryAttribute('gis', $location);
        $model->located_at = time();
//        $model->gis = 'POINT(108.9465236664 34.98766768)';
        $updated = $model->save();
        if (YII_DEBUG && !$updated) {
            Yii::error($model->getErrors());
        }
        return $updated;
    }

    public static function clearLocation($uid) {
        $model = static::findOrNew($uid);
        if ($model->isNewRecord) {
            $model->id = $uid;
        }
        $model->setGeometryAttribute('gis', null);
        $model->located_at = 0;
        $updated = $model->save();
        if (YII_DEBUG && !$updated) {
            Yii::error($model->getErrors());
        }
        return $updated;
    }

    public static function createAccount($uid) {
        $model = static::findOrNew($uid);
        if (!$model->isNewRecord) {
            return $model;
        }
        $model->id = $uid;

        $inlogs = TrendLog::find()
        ->select(['type', 'sum(num) amount'])
        ->andWhere(['user_id' => $uid])
        ->andWhere(['>', 'num', 0])
        ->groupBy('type')
        ->asArray()
        ->all();
        $ins = ArrayHelper::map($inlogs, 'type', 'amount');

        $outlogs = TrendLog::find()
        ->select(['type', 'sum(num) amount'])
        ->andWhere(['user_id' => $uid])
        ->andWhere(['<', 'num', 0])
        ->groupBy('type')
        ->asArray()
        ->all();
        $outs = ArrayHelper::map($outlogs, 'type', 'amount');

        $accountType = [
            'credit' => UserAccount::TYPE_CREDIT,
            'gold' => UserAccount::TYPE_GOLD,
            'cash' => UserAccount::TYPE_CASH,
            'exp' => UserAccount::TYPE_EXP,
        ];

        $accountAttributes = [];
        $trendAttributes = [];
        foreach ($accountType as $type => $tv) {
            $_in = ArrayHelper::getValue($ins, $type, 0);
            $_out = ArrayHelper::getValue($outs, $type, 0);
            $accountAttributes[$tv] = [
                'user_id' => $uid,
                'current' => $_in + $_out,
                'in' => $_in,
                'out' => $_out,
            ];
            if ($type == 'exp') {
                $trendAttributes['experience'] = $_in + $_out;
            }
            if ($type == 'credit') {
                $trendAttributes['credit'] = $_in + $_out;
            }
            if ($type == 'gold') {
                $trendAttributes['gold'] = $_in + $_out;
            }
            if ($type == 'cash') {
                $trendAttributes['cash'] = $_in + $_out;
            }
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            foreach ($accountAttributes as $type => $attr) {
                $uc = UserAccount::findOrNew([
                    'user_id' => $uid,
                    'type' => $type,
                ]);
                $uc->attributes = $attr;
                if (!$uc->save()) {
                    throw new Exception($uc->getErrorMsg());
                }
            }
            $model->attributes = $trendAttributes;
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return $model;
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'level',
            'experience',
            'credit',
            'gold',
            'cash',
            'liveness',
            'likes',
        ];
    }

}
